﻿using QRCoder;
using System.Drawing;

namespace CoreHelper
{
    /// <summary>
    /// 二维码帮助类
    /// </summary>
    public static class QRHelper
    {
        #region 生成二维码
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="url">内容</param>
        /// <param name="pixel">像素大小</param>
        /// <returns>图片对象</returns>
        public static Bitmap GetQRCode(string url, int pixel)
        {
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData codeData = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.H, true);
            QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData);
            Bitmap qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, true);
            return qrImage;
        }
        #endregion

        #region 生成二维码并添加文本水印
        /// <summary>
        /// 生成二维码并添加文本水印
        /// </summary>
        /// <param name="url">二维码内容</param>
        /// <param name="pixel">像素大小</param>
        /// <param name="WaterText">文本水印</param>
        /// <param name="fontsize">文本水印字体大小</param>
        /// <returns></returns>
        public static Bitmap GetQRCode(string url, int pixel, string WaterText, int fontsize = 20)
        {
            #region 生成二维码
            var qrGenerator = new QRCodeGenerator();
            var qrCodeData = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.H);
            var qrCode = new QRCode(qrCodeData);
            var qrCodeImage = qrCode.GetGraphic(pixel, Color.Black, Color.White, true);
            #endregion

            int _addheight = 50;//新画布高度，在二维码高度基础上增加
            var bitmap = new Bitmap(pixel, pixel + _addheight);//宽，高
            var g = Graphics.FromImage(bitmap);
            var font = new Font("SimSun", fontsize, FontStyle.Bold);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            g.Clear(Color.White);
            g.DrawImage(qrCodeImage, 0, 0, pixel, pixel);

            var sbrush = new SolidBrush(Color.Black);

            #region 水印文本居中对齐
            var stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;//居中字符串
            stringFormat.LineAlignment = StringAlignment.Center;//左、右对齐 
            #endregion

            g.DrawString(WaterText, font, sbrush, pixel / 2, pixel + _addheight / 2, stringFormat);
            g.Dispose();
            //var tempFilePath = Path.Combine("C:\\QRCode.png");
            //bitmap.Save(tempFilePath);
            return bitmap;
        }
        #endregion

        /*  调用示例：
            //保存到磁盘
            var bitmap = _iQRCode.GetQRCode(url, pixel);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            //输出到浏览器
            Response.ContentType = "image/jpeg";
            Response.Body.WriteAsync(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
            Response.Body.Close();
         */



    }
}